package com.flower.droid;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;


public class FlowerView extends SurfaceView implements SurfaceHolder.Callback{
	class FlowerThread extends Thread
	{
		public static final int STATE_PAUSE = 1;
		public static final int STATE_READY = 2;
		public static final int STATE_RUNNING = 3;
		public static final int STATE_EXIT = 4;
		public static final int STATE_OPTIONS = 5;
		public static final int STATE_CREDITS = 6;
		public static final int STATE_INFO = 7;
		
		private int mCanvasHeight = 1;
		private int mCanvasWidth = 1;
		
		/** Message handler used by thread to interact with TextView */
        private Handler mHandler;
        /** The state of the game. One of READY, RUNNING, PAUSE, LOSE, or WIN */
        private int mMode;
        /** Indicate whether the surface has been created & is ready to draw */
        private boolean mRun = false;
        /** Scratch rect object. */
        private RectF mScratchRect;
        /** Handle to the surface manager object we interact with */
        private SurfaceHolder mSurfaceHolder;
        /** Used to figure out elapsed time between frames */
        private long mLastTime;
        
        public boolean mShowOptions = false;
        
        /** The drawable to use as the background of the animation canvas */
        private Bitmap mBackgroundImage = null;
        
        
        private Display display;
        
        public boolean started = false;
        
        public FlowerThread(SurfaceHolder surfaceHolder, Context context, Handler handler)
        {
        	mSurfaceHolder = surfaceHolder;
        	mHandler = handler;
        	mContext = context;
        	
        	mScratchRect = new RectF(0, 0, 0, 0);
        	
        	Resources res = context.getResources();
        	if(mBackgroundImage == null)
        		mBackgroundImage = BitmapFactory.decodeResource(res, R.drawable.prout2);
        	
        	mRun = false;
        }
        
        public void setDisplay(Display dis)
        {
        	display = dis;
        }
        
        
        public void doStart()
        {
        	synchronized(mSurfaceHolder)
        	{        		
        		mRun = true;
        		started = true;
        		
            	mLastTime = System.currentTimeMillis() + 100;
        	}
        }
        
        public void pause() {
            synchronized (mSurfaceHolder) {
                if (mMode == STATE_RUNNING) setState(STATE_PAUSE);
            	
            }
        }
        
        public synchronized void restoreState(Bundle savedState) {
            synchronized (mSurfaceHolder) {
                setState(STATE_RUNNING);
               
            }
        }
        
        @Override
        public void run() {
            while (mRun) {
                Canvas c = null;
                try {
                    c = mSurfaceHolder.lockCanvas(null);
                    synchronized (mSurfaceHolder) {
                        if (mMode == STATE_RUNNING) 
                        	Update();
                        doDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        mSurfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
        
        public Bundle saveState(Bundle map) {
            synchronized (mSurfaceHolder) {
                if (map != null) {
                   
                }
            }
            return map;
        }
        
        public void setRunning(boolean b) {
            mRun = b;
        }
        
        public void setState(int mode) {
            synchronized (mSurfaceHolder) {            	
            	mMode = mode;
            	if(mMode == STATE_EXIT)
            		mRun = false;
            }
        }
        
        /* Callback invoked when the surface dimensions change. */
        public void setSurfaceSize(int width, int height) {
            // synchronized to make sure these all change atomically
            synchronized (mSurfaceHolder) {
                mCanvasWidth = width;
                mCanvasHeight = height;

                // don't forget to resize the background image
               // mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, width, height, true);
            }
        }
        
        public void unpause() {
            // Move the real time clock up to now
            synchronized (mSurfaceHolder) {
            	//this.resume();
                mLastTime = System.currentTimeMillis() + 100;
            }
            setState(STATE_RUNNING);
        }
        
        boolean doKeyDown(int keyCode, KeyEvent msg) {
            synchronized (mSurfaceHolder) {

                return false;
            }
        }
        
        public void checkInput(int x, int y)
        {
        	if(mMode != STATE_OPTIONS)
        	{
        		if(x < 100 && x > 0 && y > 0 && y < 100)
        		{
        			//setState(STATE_OPTIONS);
        		}        	
        	}
        	else if(mMode == STATE_OPTIONS)
        	{
        		if(x < 100 && x > 0 && y > 0 && y < 100)
        		{
        			//setState(STATE_RUNNING);
        		} 
        	}
        }
        
        boolean doKeyUp(int keyCode, KeyEvent msg) {
            boolean handled = false;

            synchronized (mSurfaceHolder) {
                if (mMode == STATE_RUNNING) {
                   
                }
            }

            return handled;
        }
        
        
        /*
         * HTC EVO = 480 x 800
         */
        
        private void doDraw(Canvas canvas) {
            // Draw the background image. Operations on the Canvas accumulate
            // so this is like clearing the screen.

        	//canvas.drawBitmap(mBackgroundImage, 0, 0, null);
        	
			//if (mResized == null) {
				/*int w = mBackgroundImage.getWidth();
				int h = mBackgroundImage.getHeight();

				DisplayMetrics dm = new DisplayMetrics();
				display.getMetrics(dm);
				int nW = dm.widthPixels;
				int nH = dm.heightPixels;

				float sW = ((float) nW) / w;
				float sH = ((float) nH) / h;

				// fucking with your aspects!
				// if (sW > sH) sW = sH;
				// if (sH > sW) sH = sW;

				Matrix matrix = new Matrix();
				matrix.postScale(sW, sH);
				mResized = Bitmap.createBitmap(mBackgroundImage, 0, 0, w, h, matrix, true);*/
			//}
        	
        	canvas.drawBitmap(mBackgroundImage, 0, 0, null);
        	
        	
            canvas.save();
           
            canvas.restore();
        }
        
        private void Update()
        {
        	long now = System.currentTimeMillis();
        	if (mLastTime > now) return;
        	
        	double elapsed = (now - mLastTime) / 1000.0;
        	
        	
        	mLastTime = now;
        	
        	
        }
        
		
	}
	//BELOW HERE IS FLOWERVIEW!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	
	/** Handle to the application context, used to e.g. fetch Drawables. */
    private Context mContext;

    /** Pointer to the text view to display "Paused.." etc. */
    private TextView mStatusText;

    /** The thread that actually draws the animation */
    private FlowerThread thread;
    
	
    public FlowerView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // register our interest in hearing about changes to our surface
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);

        // create thread only; it's started in surfaceCreated()
        thread = new FlowerThread(holder, context, new Handler() {
            @Override
            public void handleMessage(Message m) {
                mStatusText.setVisibility(m.getData().getInt("viz"));
                mStatusText.setText(m.getData().getString("text"));
            }
        });

        setFocusable(true); // make sure we get key events
    }
    
    public FlowerThread getThread()
    {
    	return thread;
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent msg) {
        return thread.doKeyDown(keyCode, msg);
    }
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent msg) {
        return thread.doKeyUp(keyCode, msg);
    }
	
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        if (!hasWindowFocus)
        	thread.pause();
        else
        	thread.unpause();
    }

    public void setTextView(TextView textView) {
        mStatusText = textView;
    }
    
    
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		// TODO Auto-generated method stub
		thread.setSurfaceSize(width, height);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		thread.setRunning(true);
		if(!thread.isAlive())
			thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		boolean retry = true;
        thread.setRunning(false);
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
	}
	
	
}